#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FastAPI应用主文件
负责创建和配置FastAPI应用实例
"""

import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager

from app.api.v1.router import api_router
from app.core.config import settings
from utils.logger import get_logger
from utils.config_manager import get_config_manager, get_app_config, get_api_config

logger = get_logger(__name__)

# 初始化配置管理器
config_manager = get_config_manager()
app_config = get_app_config()
api_config = get_api_config()


def create_app() -> FastAPI:
    """
    创建FastAPI应用实例
    
    Returns:
        FastAPI: 配置好的FastAPI应用实例
    """
    # 创建FastAPI应用
    app = FastAPI(
        title=api_config.get("title", "API Test Demo"),
        version=api_config.get("version", "1.0.0"),
        description=api_config.get("description", "API自动化测试演示项目"),
        openapi_url=f"{api_config.get('prefix', '/api/v1')}/openapi.json",
        debug=app_config.get("debug", False)
    )
    
    # 设置 CORS
    cors_config = config_manager.get("cors", {})
    app.add_middleware(
        CORSMiddleware,
        allow_origins=cors_config.get("origins", ["*"]),
        allow_credentials=cors_config.get("credentials", True),
        allow_methods=cors_config.get("methods", ["*"]),
        allow_headers=cors_config.get("headers", ["*"]),
    )
    
    # 包含路由
    app.include_router(api_router, prefix=api_config.get("prefix", "/api/v1"))
    
    return app


# 创建应用实例
app = create_app()


@app.get("/")
async def root():
    """根路径接口"""
    return {
        "message": "欢迎使用API测试Demo",
        "version": settings.VERSION,
        "docs": "/docs"
    }


@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "message": "服务运行正常",
        "version": settings.VERSION
    }


@app.get("/api/version")
async def api_version():
    """API版本信息接口"""
    return {
        "version": settings.VERSION,
        "api_version": "v1",
        "name": "API Test Demo",
        "description": "FastAPI接口测试示例项目"
    }